<?php

namespace App\Console\Commands\Cruise;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Clickhouse\Guanyuan\GyDailyDeliveryReportCHModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseShopAccountModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Orm\OrmNewOrderRemote;
use Carbon\Carbon;
use Illuminate\Console\Command;

class UpdateShopOrderAmount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:update-shop-order-amount';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新门店的营业额与订货金额，同步冗余字段';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '512M');

        // 截断表
        CruiseShopAccountModel::query()->truncate();

        // 已开业的门店code
        $shopBusinessCHModelCollection = GyDailyDeliveryReportCHModel::query()
            ->where("date", ">", Carbon::now()->subDays(7)->toDateString())
            ->where('storeCode', ">", 0)
            ->select(['storeCode'])
            ->get();
        $shopBusinessList = collect($shopBusinessCHModelCollection)->pluck('storeCode')->toArray();

        // 添加表数据
        OpenShopSignOrderModel::query()
            ->whereIn('status', [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE])
            ->with(['addressRel', 'shopRel', 'identityCardRel'])
            ->chunk(100, function ($singOrders) use ($shopBusinessList){
                // 获得门店预计开业时间
                $orderNos       = collect($singOrders)->pluck('orderNo')->toArray();
                $mainProcessIds = collect($singOrders)->pluck('mainProcessId', 'orderNo')->toArray();

                $preOpenTime = OpenShopSiteLocationModel::query()
                    ->whereIn('orderNo', $orderNos)
                    ->where('openTime', '>', 0)
                    ->pluck('openTime', 'orderNo')
                    ->toArray();

                $managerNameList = OpenShopOrderManagerModel::query()
                    ->whereIn('mainProcessId', array_values($mainProcessIds))
                    ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                    ->pluck('managerName', 'mainProcessId')
                    ->toArray();

                $orderManagerName = [];
                foreach ($mainProcessIds as $orderNo => $mainProcessId) {
                    $orderManagerName[$orderNo] = $managerNameList[$mainProcessId] ?? '-';
                }

                foreach ($singOrders as $singOrder) {
                    if ($singOrder->shopRel == null) {
                        continue;
                    }

                    //过滤掉RMS门店状态为停用的
                    if ($singOrder->shopRel->status == RmsShopApi::SHOP_STATUS_OFF) {
                        continue;
                    }

                    $shopId       = $singOrder->shopRel->id;
                    $ormOrderList = OrmNewOrderRemote::getNewOrderByShopId($shopId);
                    if ($ormOrderList['code'] == 0 && count($ormOrderList['data'])) {
                        $orderAmount = array_sum(array_column($ormOrderList['data'], 'total_amount')) * 100;
                    } else {
                        $orderAmount = 0;
                    }
                    $turnover                      = (new RmsShopApi())->originalPrice($shopId, strtotime('-30day'), time())['data']['originalPrice'] ?? 0;
                    $shopGradeData                 = (new RmsShopApi())->shopBusiness([$shopId], ['shopId', 'shopGrade'])['data'] ?? [];
                    $shopGrade                     = count($shopGradeData) ? array_column($shopGradeData, 'shopGrade', 'shopId') : [];
                    $shopAccountModel              = CruiseShopAccountModel::query()
                        ->firstOrNew([
                            'shopId' => $shopId
                        ]);
                    $shopGradeText = $shopGrade[$shopId] ?? '-';
                    switch ($shopGradeText) {
                        case '明星':
                            $shopGrade = OpenShopSiteLocationModel::HOUSE_GRADE_STAR;
                            break;
                        case '金牛':
                            $shopGrade = OpenShopSiteLocationModel::HOUSE_GRADE_TAURUS;
                            break;
                        case '瘦狗':
                            $shopGrade = OpenShopSiteLocationModel::HOUSE_GRADE_SKINNY_DOG;
                            break;
                        default:
                            $shopGrade = OpenShopSiteLocationModel::HOUSE_GRADE_QUESTION;
                    }

                    // 获得门店的最近巡店时间
                    $cruiseId = (int)CruiseOrderModel::query()
                        ->where('shopId', $shopId)
                        ->whereIn('type', [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5])
                        ->orderByDesc('id')
                        ->value('id');

                    if ($cruiseId == 0) {
                        $daysWithoutCruise = 999;
                    } else {
                        $cruiseSubmitTime = (int)CruiseCheckDetailModel::query()
                            ->where('orderId', $cruiseId)
                            ->orderByDesc('id')
                            ->value('submitTime');
                        $daysWithoutCruise = $cruiseSubmitTime ? Carbon::now()->diffInDays(Carbon::createFromTimestamp($cruiseSubmitTime)) : 0;
                    }

                    $shopAccountModel->orderAmount       = $orderAmount;
                    $shopAccountModel->shopCode          = $singOrder->shopCode;
                    $shopAccountModel->orderNo           = $singOrder->orderNo;
                    $shopAccountModel->shopName          = $singOrder->shopRel->name;
                    $shopAccountModel->area              = (string)optional($singOrder->addressRel)->addressPrefix;
                    $shopAccountModel->preOpenTime       = $preOpenTime[$singOrder->orderNo] ?? 0;
                    $shopAccountModel->managerName       = $orderManagerName[$singOrder->orderNo] ?? '-';
                    $shopAccountModel->provinceCode      = (int)optional($singOrder->addressRel)->provinceCode;
                    $shopAccountModel->cityCode          = (int)optional($singOrder->addressRel)->cityCode;
                    $shopAccountModel->districtCode      = (int)optional($singOrder->addressRel)->areaCode;
                    $shopAccountModel->franchiseeName    = (string)optional($singOrder->identityCardRel)->name;
                    $shopAccountModel->businessStatus    = (int)in_array($singOrder->shopCode, $shopBusinessList);
                    $shopAccountModel->daysWithoutCruise = $daysWithoutCruise;
                    $shopAccountModel->turnover          = $turnover;
                    $shopAccountModel->shopGrade         = $shopGrade;
                    $shopAccountModel->orderRatioNumber  = $turnover ? (round($orderAmount / $turnover, 2) * 100) : 0;
                    $shopAccountModel->save();
                    $this->info('门店ID为' . $shopId . '已同步');
                }
            });
    }
}
